<?php
namespace Utuo;

use Utuo\Wechat\Snoopy;

class Express {

	private $expressname = array ( 'shentong' => '申通快递', 'ems' => 'E邮宝', 'yuantong' => '圆通快递', 
						'zhongtong' => '中通快递', 'zengyisudi' => '增益', 'yunda' => '韵达快递', 'tiantian' => '天天快递', 'huitongkuaidi' => '汇通快递', 
						'quanfengkuaidi' => '全峰快递', 'debangwuliu' => '德邦物流', 'zhaijisong' => '宅急送', 'auspost' => '澳大利亚邮政', 'anposten' => 'An Post', 
						'youzhengguonei' => '包裹平邮', 'bangsongwuliu' => '邦送物流', 'brazilpost' => '巴西邮政', 'dhl' => 'DHL快递', 'datianwuliu' => '大田物流', 
						'danmarkpost' => '丹麦邮政', 'emsguoji' => 'EMS国际', 'rufengda' => '如风达', 'fedex' => 'FedEx(国际件)', 'guotongkuaidi' => '国通快递', 
						'gongsuda' => '共速达', 'youzhengguoji' => '国际小包', 'tiandihuayu' => '天地华宇', 'huiqiangkuaidi' => '汇强快递', 'jiajiwuliu' => '佳吉快运', 
						'jiayiwuliu' => '佳怡物流', 'canpost' => '加拿大邮政', 'kuaijiesudi' => '快捷速递', 'longbanwuliu' => '龙邦速递', 'lianbangkuaidi' => '联邦快递', 
						'lianhaowuliu' => '联昊通', 'ganzhongnengda' => '能达速递', 'ruidianyouzheng' => '瑞典邮政', 'japanpost' => '日本邮政', 
						'quanyikuaidi' => '全一快递', 'quanritongkuaidi' => '全日通', 'shunfeng' => '顺丰快递', 'suer' => '速尔快递', 'tnt' => 'TNT快递', 
						'ups' => 'UPS快递', 'usps' => 'USPS(美国邮政)', 'xinbangwuliu' => '新邦物流', 'neweggozzo' => '新蛋物流', 'hkpost' => '香港邮政',
						'youshuwuliu' => '优速快递', 'zhongtiewuliu' => '中铁快运', 'zhongyouwuliu' => '中邮物流', );
	
	private $config = array(
		'fake' => 0, // 伪造ip
		'new' => 0,
	);
	
	/**
	 * 获得实例
	 * @param unknown $driver
	 * @param unknown $config
	 * @return \Utuo\Pay
	 */
	public final static function getInstance($config) {
		static $instance;
		if(!$instance) $instance = new Express($config);
		return $instance;
	}
	
	
	function __construct($config) {
		$this->config = array_merge($this->config, $config == null?array():$config);
		$this->expressname();
	}

	
	private function getcontent($url, $query) {
		if (function_exists('curl_init') == 1) {
			$curl = curl_init();
			curl_setopt ($curl, CURLOPT_URL, $url);
			curl_setopt ($curl, CURLOPT_HEADER, 0);
			curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
			//curl_setopt ($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
			curl_setopt ($curl, CURLOPT_TIMEOUT, 5);
			curl_setopt ($curl, CURLOPT_REFERER, "http://m.kuaidi100.com");
			$get_content = curl_exec($curl);
			curl_close ($curl);
		}else{
			$snoopy = new Snoopy();
			$snoopy->referer = 'http://www.google.com/';//伪装来源
			$snoopy->fetch($url);
			$get_content = $snoopy->results;
		}
		return $get_content;
	}
	
	/*
	 * 采集网页内容的方法
	private function getcontent($url, $query) {
		if(function_exists("fsockopen")) {
			$info = parse_url($url);
			$fp = fsockopen($info["host"], 80, $errno, $errstr, 30);
			$head = "GET ".$info['path']."?".$info["query"]." HTTP/1.1\r\n";
			$head .= "Host:".$info['host']."\r\n";
			if($this->config["fake"] ) {
				$head.= "Referer: http://www.wmfl.com/\r\n";
				$head.= "Client-IP: 192.168.0.1\r\n";
				$head.= "X-Forwarded-For: 192.168.0.1\r\n"; //主要是这里来构造IP
			}
			$head.= "Connection: Close\r\n";
			$head.= "\r\n";
			$write = fputs($fp, $head);
			$file_contents = "";
			while (!feof($fp)) $file_contents .= fread($fp,4096);
			fclose($fp);
			$file_contents = trim(substr($file_contents, strpos($file_contents, "\r\n\r\n")));
		} elseif (function_exists("file_get_contents")) {
			$file_contents = file_get_contents($url);
		} else {
			$ch = curl_init();
			$timeout = 5;
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
			$file_contents = curl_exec($ch);
			curl_close($ch);
		}
		return $file_contents;
	}*/

	/*
	 * 获取对应名称和对应传值的方法
	*/
	private function expressname(){
		if($this->config['new']) {
			$result = $this->getcontent("http://www.kuaidi100.com/");
			preg_match_all("/data\-code\=\"(?P<name>.*)\"(.*)?\>\<span\>(?P<title>.*)\<\/span>/isU", $result, $data);
			$name = array();
			foreach($data['title'] as $k=>$v){
				$name[$data['name'][$k]] = $v;
			}
			$this->expressname = $name;
		}
		return $this->expressname;
	}

	/*
	 * 解析object成数组的方法
	* @param $json 输入的object数组
	* return $data 数组
	*/
	private function json_array($json){
		if($json){
			foreach ((array)$json as $k=>$v){
				$data[$k] = !is_string($v)?$this->json_array($v):$v;
			}
			return $data;
		}
	}
	
	/**
	 * 物流外链
	 * @param unknown $name
	 * @param unknown $order
	 * @return string
	 */
	public function getLinkUrl( $name, $order ) {
		if ( empty($name) or empty($order) ) {
			return "";
		}
		
		foreach ($this->expressname as $k => $v) {
			if($v == $name) {
				$keywords = $k;
				break;
			}
		}
		return "http://m.kuaidi100.com/index_all.html?type={$keywords}&postid={$order}";
	}
	
	function pget($url,$cookie){
		$curl = curl_init(); // 启动一个CURL会话
		curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
		curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
		curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
		//curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
		curl_setopt($curl, CURLOPT_REFERER, "http://www.kuaidi100.com/");
		curl_setopt($curl, CURLOPT_HTTPGET, 1); // 发送一个常规的Post请求
		curl_setopt($curl, CURLOPT_COOKIEJAR, $GLOBALS['cookie_file']); // 存放Cookie信息的文件名称
		curl_setopt($curl, CURLOPT_COOKIEFILE,$GLOBALS ['cookie_file']); // 读取上面所储存的Cookie信息
		curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
		curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
		$tmpInfo = curl_exec($curl); // 执行操作
		if (curl_errno($curl)) {
			echo '操作超时!';
		}
		curl_close($curl); // 关键CURL会话
		return $tmpInfo; // 返回数据
	}

	/*
	 * 返回$data array      快递数组
	* @param $name         快递名称
	* 支持输入的快递名称如下
	* (申通-EMS-顺丰-圆通-中通-如风达-韵达-天天-汇通-全峰-德邦-宅急送-安信达-包裹平邮-邦送物流
			* DHL快递-大田物流-德邦物流-EMS国内-EMS国际-E邮宝-凡客配送-国通快递-挂号信-共速达-国际小包
			* 汇通快递-华宇物流-汇强快递-佳吉快运-佳怡物流-加拿大邮政-快捷速递-龙邦速递-联邦快递-联昊通
			* 能达速递-如风达-瑞典邮政-全一快递-全峰快递-全日通-申通快递-顺丰快递-速尔快递-TNT快递-天天快递
			* 天地华宇-UPS快递-新邦物流-新蛋物流-香港邮政-圆通快递-韵达快递-邮政包裹-优速快递-中通快递)
	* 中铁快运-宅急送-中邮物流
	* @param $order        快递的单号
	* $data['ischeck'] ==1   已经签收
	* $data['data']        快递实时查询的状态 array
	*/
	public  function getorder($name, $order) {
		
		if ( empty($name) or empty($order) ) {
			return array(
				'status' => 201,
				'message' => '发货单号不正确',
			);
		}
		
		foreach ($this->expressname as $k => $v) {
			if($v == $name) {
				$keywords = $k; 
				break;
			}
		}
		
// 		echo "http://m.kuaidi100.com/query?type={$keywords}&postid={$order}";
		$result = $this->getcontent("http://m.kuaidi100.com/query?type={$keywords}&postid={$order}&temp=".time());
// 		dump($result);
		$result = json_decode($result);
		$data = $this->json_array($result);
		
		if( $data['status'] == 201 ) {
			$data['message'] = "该订单暂无流转信息";
		}
		
		if ( $data['status'] == 200 and !empty($data['data']) ) {
			cookie($order, serialize($data));
		} elseif( cookie($order) ) {
			$data = unserialize(cookie($order));
		}
		
		return $data;
	}

	/**
	 * 全部快递数据
	 */
	public function getExpressname() {
		return $this->expressname;
	}
}

// $express = \Utuo\Express::getInstance();
// $result = $express->getorder("全一快递","111309582915");
// var_dump($result);